package com.gdth.bank.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.gdth.bank.R;
import com.gdth.bank.activity.BaiduMapActivity;
import com.gdth.bank.activity.BaiduMapActivityTwo;
import com.gdth.bank.activity.CjkhjlActivity;
import com.gdth.bank.adapter.CjkhBfjlListViewAdapter;
import com.gdth.bank.event.CjkhjlListEvent;
import com.gdth.bank.presenter.CjkhBfrjPresenter;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.view.CjkhBfrjView;
import com.gdth.bank.widget.BankDrawDownListTextView;
import com.gdth.bank.widget.baiduMap.LocationBean;
import com.gdth.bank.widget.listener.TextWatcherListener;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseFrameLayout;
import com.gdth.database.bean.TAppBfrjBfjl;
import com.gdth.model.ImageItem;
import com.gdth.model.Item;
import com.gdth.utils.DateTimeUtil;
import com.gdth.utils.UUIDUtil;

import org.greenrobot.eventbus.EventBus;


/**
 * 采集客户基本信息页面
 * @author arvin
 *
 */
public class CjkhBfrjFragment extends BaseFrameLayout implements CjkhBfrjView{
	TAppBfrjBfjl mTAppBfrjBfjl;
	
	private String jcuuid;
	private String khxm;
	private int create = 0, update = 1;
	
	@ViewInject(id=R.id.bfjl_zslp) EditText edit_zslp;
	@ViewInject(id=R.id.bfjl_grzj) EditText edit_grzj;
	@ViewInject(id=R.id.bfjl_bfdz) EditText edit_bfdz;
	@ViewInject(id=R.id.bfjl_save )
	Button bfjl_save;
	@ViewInject(id=R.id.bfjl_add )
	Button kfbf_save_bnt;
	@ViewInject(id=R.id.bfjl_change )
	Button bfjl_change;

	@ViewInject(id=R.id.cjkh_bflx) BankDrawDownListTextView drawDownList_bflx;
	@ViewInject(id=R.id.cjkh_map)
	ImageButton txt_map;
	@ViewInject(id=R.id.bfjl_listview, itemClick="onItemClick") ListView listView_bfjl;
	@ViewInject(id=R.id.root_layout) LinearLayout root_layout;

	CjkhBfjlListViewAdapter adapter;
	
	CjkhjlActivity activity;
	
	List<TAppBfrjBfjl> bfjlList;
	
	List<Item> bflxList = new ArrayList<Item>();
	
	CjkhBfrjPresenter presenter;
	
	List<ImageItem> items;
	
	String address;
	float jd,wd;
	String hquuid="";
	int  id=0;
	Long zhId;
	double Latitude ;
	double Longitude ;
	String check="";
	
	public CjkhBfrjFragment(Context context){
		super(context, R.layout.fragment_cjkhjl_khxx);
		
		activity = (CjkhjlActivity) context;
	}
	
	public void initializeView(){
//		txt_map.setImage(ImageUtil.getImageAsDrawable(this.context, R.drawable.map_point));
		//txt_map.setLabel(R.string.cjkh_khxx_zfdz);
		txt_map.setOnClickListener(new OnMapClickListener(""));
		
		edit_zslp.addTextChangedListener(new TextWatcherListener(context, edit_zslp, 100));
		edit_grzj.addTextChangedListener(new TextWatcherListener(context, edit_grzj, 500));
		edit_bfdz.addTextChangedListener(new TextWatcherListener(context, edit_bfdz, 100));
		
		bflxList = AppUtil.getCanshuByType(this.context, AppUtil.SHARE_DATA_BFLX);
		drawDownList_bflx.setLabel("拜访类型：");
		drawDownList_bflx.setItem(bflxList);
		drawDownList_bflx.setValue("1");
		edit_bfdz.setEnabled(false);
		drawDownList_bflx.setOnSelectListener(new onBflxListener());
		
		root_layout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

			@Override
			public void onGlobalLayout() {
				// TODO Auto-generated method stub
				//比较Activity根布局与当前布局的大小
		        int heightDiff = root_layout.getRootView().getHeight() - root_layout.getHeight();
		        if(heightDiff > 600){
		        	//大小超过100时，一般为显示虚拟键盘事件
		        	listView_bfjl.setVisibility(View.GONE);
		        }else{
		        	//大小小于100时，为不显示虚拟键盘或虚拟键盘隐藏
		        	listView_bfjl.setVisibility(View.VISIBLE);
		       }
			}
			
		});
		bfjl_save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				save();
			}
		});
		kfbf_save_bnt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				reset();
			}
		});
		bfjl_change.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				edit();
			}
		});
	}
	
	public void initializePresenter(){
		presenter = new CjkhBfrjPresenter(this);
		bfjlList = new ArrayList<TAppBfrjBfjl>();
		adapter = new CjkhBfjlListViewAdapter(this.context, bfjlList);
		adapter.setBflx(bflxList);
		adapter.setmOnJtcyXxDetailClickListener(new CjkhBfjlListViewAdapter.OnbfjlDetailClickListener() {
			@Override
			public void clickListener(int position) {
				presenter.DelBfjl(bfjlList.get(position));
			}
		});
		listView_bfjl.setAdapter(adapter);
		

	}

	public void saveOrUpdate(int type) {
		String bflx = drawDownList_bflx.getkey().toString();
		String zslp = edit_zslp.getText().toString();
		String grzj = edit_grzj.getText().toString();
		String bfdz = edit_bfdz.getText().toString();
		if (bflx.equals("")) {
			showMessage("拜访类型不能为空");
			return;
		}
//		if (grzj.equals("")) {
//			showMessage("个人总结不能为空");
//			return;
//		}
		if (bflx.equals("1") || bflx.equals("2")) {
			if (bfdz.equals("")) {
				showMessage("拜访地址不能为空");
				return;
			}
		}
		if(id==0  &&  hquuid.equals("")){
			mTAppBfrjBfjl = new TAppBfrjBfjl();
			Date date = new Date();
			mTAppBfrjBfjl.setBflx(Integer.valueOf(bflx));
			mTAppBfrjBfjl.setUuid(UUIDUtil.getUUID());
			mTAppBfrjBfjl.setCjsj(date);
			mTAppBfrjBfjl.setBfrq(date);
			mTAppBfrjBfjl.setBbh(1);
			mTAppBfrjBfjl.setSjzt(AppUtil.sjzt_create);
			mTAppBfrjBfjl.setJcuuid(jcuuid);
			mTAppBfrjBfjl.setZslp(zslp);
			mTAppBfrjBfjl.setBfdz(bfdz);
			mTAppBfrjBfjl.setGrzj(grzj);
			int j=0;
			if(bfjlList.size()>0 || bfjlList!=null ){
				for(TAppBfrjBfjl tTAppBfrjBfjl:bfjlList){
				String timebj =	DateTimeUtil.getCurrentTime(tTAppBfrjBfjl.getCjsj(), "yyyy-MM-dd");
				String  now = DateTimeUtil.getCurrentTime(new Date(), "yyyy-MM-dd");
				String lx=String.valueOf(tTAppBfrjBfjl.getBflx());
					if(timebj.trim().equals(now.trim()) && lx.equals(bflx)){
						j++;
				        		}
						}
			    	}
			if (jd != 0) {
				mTAppBfrjBfjl.setJd(jd);
				mTAppBfrjBfjl.setWd(wd);
			}
			if(j==0){
				presenter.save(mTAppBfrjBfjl, 0);
			}else{
				showMessage("当天拜访类型记录只能保存一条");
			}
		}else if(id!=0 &&  hquuid !=null && mTAppBfrjBfjl !=null){
			Date mDate = mTAppBfrjBfjl.getCjsj();
			mTAppBfrjBfjl.setBbh(mTAppBfrjBfjl.getBbh() + 1);
			mTAppBfrjBfjl.setBflx(Integer.valueOf(bflx));
			mTAppBfrjBfjl.setUuid(hquuid);
			mTAppBfrjBfjl.setId(Long.parseLong(String.valueOf(id)));
			mTAppBfrjBfjl.setCjsj(mTAppBfrjBfjl.getCjsj());
			mTAppBfrjBfjl.setBfrq(mTAppBfrjBfjl.getBfrq());
			mTAppBfrjBfjl.setXgsj(new Date());
			mTAppBfrjBfjl.setBbh(1);
			mTAppBfrjBfjl.setSjzt(AppUtil.sjzt_update);
			mTAppBfrjBfjl.setJcuuid(jcuuid);
			mTAppBfrjBfjl.setZslp(zslp);
			mTAppBfrjBfjl.setBfdz(bfdz);
			mTAppBfrjBfjl.setGrzj(grzj);
			if (jd != 0) {
				mTAppBfrjBfjl.setJd(jd);
				mTAppBfrjBfjl.setWd(wd);
			}
			if(DateTimeUtil.isToday(mDate)){
				presenter.save(mTAppBfrjBfjl, 1);
			}else{
				showMessage("只有当天新增记录才可以修改保存！");
			}
			
		}
	}
	
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		TAppBfrjBfjl item = bfjlList.get(arg2);
		
		mTAppBfrjBfjl = item;
		
		setCurrentItem();
		jd = 0;
		wd = 0;
	}
	
	public void setJcuuid(String jcuuid) {
		this.jcuuid = jcuuid;
		
		presenter.getBfjlByUuid(jcuuid);
	}
	
	public void setKhxm(String khxm){
		this.khxm = khxm;
	}
	private void setCurrentItem() {
//		String time=DateTimeUtil.getCurrentTime(mTAppBfrjBfjl.getCjsj(), "yyyy-MM-dd");
//		String currently = DateTimeUtil.getCurrentTime(new Date(), "yyyy-MM-dd");
		drawDownList_bflx.setValue(mTAppBfrjBfjl.getBflx().toString());
		edit_zslp.setText(mTAppBfrjBfjl.getZslp());
		edit_grzj.setText(mTAppBfrjBfjl.getGrzj());
		edit_bfdz.setText(mTAppBfrjBfjl.getBfdz());
		hquuid = mTAppBfrjBfjl.getUuid();
		zhId = mTAppBfrjBfjl.getId();
		id = new Long(zhId).intValue();
		if(mTAppBfrjBfjl.getJd()!=null && mTAppBfrjBfjl.getJd()!=null){
		Latitude = mTAppBfrjBfjl.getJd();
		Longitude = mTAppBfrjBfjl.getWd();
		}else{
			Latitude =0.0;
			Longitude = 0.0;
		}
		check = "check";
		drawDownList_bflx.mEditText.setEnabled(false);
		edit_zslp.setEnabled(false);
		edit_grzj.setEnabled(false);
		edit_bfdz.setEnabled(false);
	}

	/**
	 * 返回定位地址
	 * @param bean
	 */
	public void setAddress(LocationBean bean){
		address = bean.getAddress();
		edit_bfdz.setText(address);
		jd = (float) bean.getJd();
		wd = (float) bean.getWd();
	}
	
	/**
	 * 点击事件
	 * @author arvin
	 *
	 */
	private class OnMapClickListener implements OnClickListener{
		private String uuid;
		
		public OnMapClickListener(String uuid) {
			this.uuid = uuid;
		}
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
//			Intent intent = new Intent(context, BaiduMapActivity.class);
			if(check.equals("")){
				intent.setClass(context, BaiduMapActivityTwo.class);
				intent.putExtra("uuid", uuid);
			}else{
			intent.setClass(context, BaiduMapActivity.class);
			intent.putExtra("uuid", uuid);
			String dz= edit_bfdz.getText().toString();
			String LatitudeStr = Double.toString(Latitude);
			String LongitudeStr = Double.toString(Longitude);
			if(LatitudeStr.toString().equals("0.0") && LongitudeStr.toString().equals("0.0") && !dz.toString().equals("")){
				intent.putExtra("dz", dz);
				intent.putExtra("LatitudeStr", LatitudeStr);
				intent.putExtra("LongitudeStr", LongitudeStr);
				intent.putExtra("khxm", khxm);
			}else if(!LatitudeStr.toString().equals("0.0") && !LongitudeStr.toString().equals("0.0") && !dz.toString().equals("")){
				intent.putExtra("dz", dz);
				intent.putExtra("LatitudeStr", LatitudeStr);
				intent.putExtra("LongitudeStr", LongitudeStr);
				intent.putExtra("khxm", khxm);
			}else{
				intent.putExtra("dz", "");
				intent.putExtra("LatitudeStr", "");
				intent.putExtra("LongitudeStr", "");
				intent.putExtra("khxm", khxm);
			 }
			}

			((Activity) context).startActivityForResult(intent, AppUtil.activity_map_requestcode, null);
		}
	};
	
	private class onBflxListener implements BankDrawDownListTextView.OnSelectListener {

		@Override
		public void onchange(String key, String value) {
			// TODO Auto-generated method stub
			if (key.equals("1") || key.equals("2")) {
				/*edit_bfdz.setFocusableInTouchMode(false); */
				edit_bfdz.setEnabled(false);
			}
			if (key.equals("3")) {
				/*edit_bfdz.setFocusableInTouchMode(false); */
				edit_bfdz.setEnabled(true);
			}
		}
		
	};
	
	@Override
	public void saveSuccess(Long id, int type) {
		// TODO Auto-generated method stub
		reset();
		if (type == create){
		mTAppBfrjBfjl.setId(id);
		bfjlList.add(mTAppBfrjBfjl);
		}
		
		adapter.notifyDataSetChanged();
		reset();
	}
	@Override
	public void getAllBrjl(List<TAppBfrjBfjl> arg0) {
		// TODO Auto-generated method stub
		bfjlList.clear();
		bfjlList.addAll(arg0);
//		for (TAppBfrjBfjl tAppBfrjBfjl : arg0) {
//			bfjlList.add(tAppBfrjBfjl);
//		}
		
		adapter.notifyDataSetChanged();
	}
	//  时间: 2020/5/9 2:25 PM ,作者: xjc, 作用: 删除办法记录
	@Override
	public void DelBfjl() {
		presenter.getBfjlByUuid(jcuuid);
	}

	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		activity.showProgressDialog(msg);
	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		activity.hideProgressDialog();
	}
	
	@Override
	public void showMessage(String msg){
		activity.showMessage(msg);
	}
	public void edit() {
		if(System.currentTimeMillis() - lastTime  < 1000) {
			return ;
		}
		lastTime = System.currentTimeMillis();
		EventBus.getDefault().post(new CjkhjlListEvent(CjkhjlListEvent.refreshList));
//		saveOrUpdate(1);
		if(mTAppBfrjBfjl!=null){
		String time=DateTimeUtil.getCurrentTime(mTAppBfrjBfjl.getCjsj(), "yyyy-MM-dd");
		String currently = DateTimeUtil.getCurrentTime(new Date(), "yyyy-MM-dd");
		if(time.toString().trim().equals(currently.toString().trim().trim())){
			drawDownList_bflx.mEditText.setEnabled(false);
			edit_bfdz.setEnabled(false);
			edit_zslp.setEnabled(true);
			edit_grzj.setEnabled(true);
		}else{
			drawDownList_bflx.mEditText.setEnabled(false);
			edit_zslp.setEnabled(false);
			edit_grzj.setEnabled(false);
			edit_bfdz.setEnabled(false);
			showMessage("历史记录不可以修改");
		}
		}
	}
	private long lastTime = 0;
	public void save() {

		if(System.currentTimeMillis() - lastTime  < 1000) {
			return ;
		}
		lastTime = System.currentTimeMillis();
		EventBus.getDefault().post(new CjkhjlListEvent(CjkhjlListEvent.refreshList));
		saveOrUpdate(0);
	}
	public void reset() {
		if(System.currentTimeMillis() - lastTime  < 1000) {
			return ;
		}
		lastTime = System.currentTimeMillis();
		EventBus.getDefault().post(new CjkhjlListEvent(CjkhjlListEvent.refreshList));
		mTAppBfrjBfjl = null;
		id = 0;
		hquuid = "";
		drawDownList_bflx.setValue("1");
		edit_zslp.setText("");
		edit_grzj.setText("");
		edit_bfdz.setText("");
		drawDownList_bflx.mEditText.setEnabled(true);
		edit_zslp.setEnabled(true);
		edit_grzj.setEnabled(true);
		check = "";
	}
	
}
